package com.qf.workqueue;

import com.qf.util.ConnectionUtil;
import com.rabbitmq.client.*;
import org.junit.Test;

import java.io.IOException;

public class Consumer {

    @Test
    public void consume1() throws Exception {
        //1. 获取连接对象
        Connection connection = ConnectionUtil.getConnection();

        //2. 创建Channel
        Channel channel = connection.createChannel();

        //3. 再次创建队列.(要求两次创建队列时的属性,必须完全一致)
        channel.queueDeclare("work_queue", true, false, false, null);

        channel.basicQos(3);

        //4. 监听队列中的消息
        channel.basicConsume("work_queue", false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者1号,获取到work_queue中的消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
        System.out.println("消费者1号开始监听消息!");
        //5. 避免程序停止
        System.in.read();
    }

    @Test
    public void consume2() throws Exception {
        //1. 获取连接对象
        Connection connection = ConnectionUtil.getConnection();

        //2. 创建Channel
        Channel channel = connection.createChannel();

        //3. 再次创建队列.(要求两次创建队列时的属性,必须完全一致)
        channel.queueDeclare("work_queue", true, false, false, null);

        channel.basicQos(3);

        //4. 监听队列中的消息
        channel.basicConsume("work_queue", false, new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者2号,获取到work_queue中的消息:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
        System.out.println("消费者2号开始监听消息!");
        //5. 避免程序停止
        System.in.read();
    }

}
